export const merge = (arr) => {
  if (!Array.isArray(arr)) return []

  return arr.reduce(
    (prev, cur) => prev[prev.length - 1] === cur ? prev : [...prev, cur],
    []
  )
}

export const sum = (arr) => arr.length === 0 ? 0 : arr.length === 1 ? arr[0] : arr[0] + sum(arr.slice(1))

export const map = (arr) => arr.reduce((prev, cur) => prev + cur)

// 二分查找 在有序数组arr中,查找target
export const find = (arr, target) => {
  // [l...n]
  let l = 0, r = arr.length - 1
  while (l <= r) {
    let mid = parseInt(l + (r - l) / 2)
    if (arr[mid] === target) return mid
    if (target < arr[mid]) {
      r = mid - 1
    } else {
      l = mid + 1
    }
  }
  return -1
}
// 递归实现
export const binarySearch = (arr, left, right, target) => {
  let l = left || 0,
    r = right || arr.length - 1,
    mid = Math.floor(l + (r - l) / 2)
  if (l <= r)
    return target === arr[mid] ? mid
      : target < arr[mid] ? binarySearch(arr, left, mid - 1, target)
        : binarySearch(arr, mid + 1, right, target)

  return -1
}